package auto.code.rap2.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import auto.code.db.utils.R;
import auto.code.db.utils.RRException;
import auto.code.rap2.entity.ClassTextInfo;
import auto.code.rap2.entity.Module;
import auto.code.rap2.utils.Rap2GenUtil;

import java.util.List;
import java.util.Map;

/**
 * rap2代码生成类
 * @author dzc
 */
@RestController
@RequestMapping("/rap2")
public class Rap2Controller {

    /**
     * rap2整个文档生成代码并且下载
     * @param param
     * @return
     * @throws Exception
     */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@PostMapping(value = "/allcode")
    public ResponseEntity<byte[]> allcode(@RequestBody Map<String, String> param) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", System.currentTimeMillis() + ".zip");
        return new ResponseEntity(Rap2GenUtil.generator(param), headers, HttpStatus.CREATED);
    }
    
    /**
     * rap2单个方法生成下载
     * @param param
     * @return
     * @throws Exception
     */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@PostMapping(value = "/singlecode")
    public ResponseEntity<byte[]> singlecode(@RequestBody Module moduleObj) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "Rap2_"+System.currentTimeMillis() + ".zip");
        return new ResponseEntity(Rap2GenUtil.singlecode(moduleObj), headers, HttpStatus.CREATED);
    }
    
    /**
     * rap2文档预览
     * @param param
     * @return
     * @throws Exception
     */
	@SuppressWarnings("static-access")
	@PostMapping(value = "/singletext")
    public R singletext(@RequestBody Module moduleObj) throws Exception {
		try {
			List<ClassTextInfo> classInfoList = Rap2GenUtil.singletext(moduleObj);
	        return new R().ok().put("data", classInfoList);
		} catch (RRException e) {
			 return new R().error(e.getLocalizedMessage());
		}
    }
}
